<template>
  <div>
    <el-checkbox-group v-model="selectedId"  v-if="type === 'checkbox'">
      <el-checkbox
                v-for="dict in (data || dictOptions || selectData)"
                :key="dict.dictValue"
                :label="dict.dictValue"
      >{{ dict.dictLabel }}
      </el-checkbox>
    </el-checkbox-group>
    <el-radio-group v-model="selectedId" v-if="type === 'radio'">
      <el-radio
                v-for="dict in (data || dictOptions || selectData)"
                :key="dict.dictValue"
                :disabled="selectDisabled"
                :label="dict.dictValue"
      >{{ dict.dictLabel }}
      </el-radio>
    </el-radio-group>
    <el-select
      v-if="type === 'select'"
      v-model="selectedId"
      :placeholder="placeholder"
      :disabled="selectDisabled"
      :multiple="multiple"
      collapse-tags
      :allow-create="allowCreate"
      :default-first-option="allowCreate"
      clearable
      filterable
      size="small"
      @change="selectLineChanged"
    >
      <el-option value="all" v-if="multiple && allBtn && !allFlag">全选</el-option>
      <el-option value="cancelAll" v-if="multiple && allBtn && allFlag">取消全选</el-option>
      <el-option v-if="(data || dataType) && (line.filter ? line.filter === filter : true)"
                 v-for="line in selectData"
                 :key="line.dictValue"
                 :label="line.dictLabel"
                 :value="line.dictValue "
      />
      <el-option v-if="dictType"
                 v-for="dict in dictOptions"
                 :key="dict.dictValue"
                 :label="dict.dictLabel"
                 :value="dict.dictValue"
      />
      <el-option value="toEdit" v-if="allowCreate">添加或编辑</el-option>

    </el-select>
  </div>
</template>

<script>
import {addData} from "@/api/system/dict/data";
import {postList} from "@/api/system/post";
export default {
  name: "elp-select-dict",
  data() {
    return {
      allFlag: false,
      selectData: [],
      dictOptions: [],
      dataMap: {},
      dictMap: {},
    }
  },
  inject: {
    elForm: {
      default: ''
    },
    elFormItem: {
      default: ''
    },
    cancel: {
      default: ''
    },
  },
  computed: {
    selectDisabled() {
      return this.disabled || (this.elForm || {}).disabled;
    },
    selectedId: {
      set: function (val) {
        if (this.multiple) {
          if (this.resultType === 'string') {
            this.$emit('input', val.join(','));
          } else {
            if (this.returnType === 'number' && val) {
              val = parseInt(val)
            }
            this.$emit('input', val);
          }
        } else {
          if (val === '') {
            val = null;
          }
          if (this.returnType === 'number' && val) {
            val = parseInt(val)
          }
          if (this.resultType === 'array') {
            this.$emit('input', [val]);
          }else{
            this.$emit("input", val);
          }
        }
      },
      get: function () {
        // console.log("get this.value:" + this.dataType, this.value)
        if (this.multiple) {
          if (!this.value) {
            return [];
          }
          if (this.resultType === 'string') {
            let strings = this.value;
            if (typeof this.value === 'string') {
              strings = this.value.split(",");
            }
            if (strings.length > 0) {
              return strings.map(item => {
                return item + "";
              });
            }
          }else{
            return this.value ;
          }
          return;
        }
        if (!this.value) {
          return "";
        }
        return this.value + "";
      },
    }
  },

  watch: {
    value: function (value) {
      console.log("watch this.value:" + this.dataType, value, this.dictOptions, this.selectData)
    },
    filter: function (value) {
      this.$emit("input", null)
    },
    data: function (value) {
      this.selectData = value
    },
    dataType: function (value) {
      console.log("watch----dataType", value)
      if (value) {
        this.dictType = ""
      }
      this.getData();
    },
    dictType: function (value) {
      if (value) {
        this.dataType = ""
      }
      // this.getData()
    },
    cascadeQuery: {
      handler: function (newVal, oldVal) {
        console.log("watch----cascadeQuery", newVal, oldVal)
        let change = false
        Object.keys(newVal).forEach(key => {
          if (oldVal[key] && newVal[key] !== oldVal[key]) {
            change = true
          }
        })
        if (change) {
          this.selectedId = ''
          this.getData();
        }
      },
      deep: true
    }
  },
  props: {
    value: {
      type: [Number, String, Array],
      default: null
    },
    filter: null,
    data: {
      type: Array,
      default: function () {
        return null
      }
    },
    // 显示方式：select radio
    type: {
      type: String,
      default: 'select'
    },
    dataType: {
      type: String,
      default: ''
    },
    dictType: {
      type: [String],
      default: ""
    },
    cascadeQuery: {
      type: Object,
      default: function () {
        return {}
      }
    },
    placeholder: {
      type: [String],
      default: "请选择"
    },
    disabled: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    allowCreate: {
      type: Boolean,
      default: false
    },
    resultType: {
      type: String,
      default: 'string' // array为数组
    },
    // 绑定的v-model 数据类型格式化
    returnType: {
      type: String,
      default: 'string' // number 为数字类型
    },
    allBtn: {
      type: Boolean,
      default: false
    },
    hasDefault:{ // 默认选择第一个
      type: Boolean,
      default: false
    },
  },
  mounted() {
    console.log("this.dictType", this.dictType)
    console.log("this.data", this.data)
    if (this.data && this.data.length > 0) {
      this.selectData = this.data.map(item=> {
        item.dictValue = item.dictValue+""
        return item
      })
      return
    }
    if (this.dictType && this.dictType.length > 0) {
      console.log("this.getDictDatas(this.dictType)", this.getDictDatas(this.dictType))
      this.dictOptions = this.getDictDatas(this.dictType).map(item=>{
        item.dictValue = item.value
        item.dictLabel = item.label
        this.dictMap[item.dictValue] = item.dictLabel
        return item;
      });
      // this.getDictDatas(this.dictType).then((response) => {
      //   this.dictOptions = response.data.map(item=>{
      //     this.dictMap[item.dictValue] = item.dictLabel
      //     return item;
      //   });
      // });
      return;
    }
    // console.log("watch----mounted", value)
    this.getData()
  },
  methods: {
    selectLineChanged(value) {
      const currentSelect = null ;
      if (this.multiple) {
        let selectAll = value.some(item => item === 'all')
        let cancelAll = value.some(item => item === 'cancelAll')
        if (selectAll) {
          this.allFlag = true
          this.selectedId = this.selectData.map(item => item.dictValue)
        } else if (cancelAll) {
          this.allFlag = false
          this.selectedId = []
        } else {
          this.selectedId = value
        }
      }
      if (this.allowCreate && value) {
        // debugger
        if (value === 'toEdit') {
          this.cancel()
          this.$router.push({
            path: '/system/dict-data/index2/' + this.dictType,
            query: {
              dictType: this.dictType
            }
          })
        }else if(!this.dictMap[value]){
          this.$confirm('确定要为字典"'+this.dictType+'"新增值："'+value+'"吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            addData({
              "dictLabel": value,
              "dictValue": value,
              "listClass": "default",
              "dictSort": 0, "status": "0", "dictType": this.dictType
            }).then(res => {
              this.getDicts(this.dictType, true).then((response) => {
                this.dictOptions = response.data;
              });
            })
          }).catch(() => {
            this.selectedId = ''
          });
        }
      }

      this.$emit("change", value, this.dataMap[value],this.dataMap);
    },
    getData() {
      if (this.dataType && this.dataType.length > 0) {
        let getDataMethod;
        let dataId = "id";
        let dataName = "name";
        switch (this.dataType) {
          case "post":
            const {postList} = require('@/api/system/post');
            getDataMethod = postList;
            dataName = "postName";
            dataId = "postId";
            break
          case "role":
            const {roleList} = require('@/api/system/role');
            getDataMethod = roleList;
            dataName = "roleName";
            dataId = "roleId";
            break

          case "bpmForm":
            const {getFormPage} = require('@/api/bpm/form');
            getDataMethod = getFormPage;
            // dataName = "hotelIdName";
            // dataId = "hotelId";
            break
          // 选择司机以外的管理员
          case "admin":
            const {listUser} = require('@/api/system/user');
            getDataMethod = listUser;
            // const {listUserSimple} = require('@/api/system/user');
            // getDataMethod = listUserSimple;
            dataName = "userName";
            dataId = "userId";
            this.cascadeQuery['exceptDriver'] = 1;
            break

          default:
            break;
        }
        if (getDataMethod !== null && getDataMethod !== undefined) {
          getDataMethod(this.cascadeQuery).then(res => {
            let rows = res.rows || res.data;
            //兼容bpm模式的返回返回参数
            if (rows.list) {
              rows = rows.list
            }
            this.selectData = rows.map(item => {
              this.dataMap[item[dataId]] = item
              if("value"!= dataId){
                    item.value = item["id"] ;
              }
              item.label = item[dataName];
              if(this.resultType == "array"){
                item.dictValue = item[dataId];
              }else{
                item.dictValue = item[dataId] + "";
              }
              item.dictLabel = item[dataName];
              if(this.dataType == "repairItem"){
                // debugger
                item.dictLabel = item.dictLabel + (item["typeName"] == null ? "" : "["+item["typeName"]+"]");
              }
              return item;
            });
            console.log("getDataMethod",this.selectData)
            if(this.hasDefault && !this.selectedId && rows){
              this.selectedId = rows[0][dataId];
              this.$emit("change");
            }
          })
        }
      }
    }
  }
}
</script>

<style scoped>
/deep/ .el-tag.el-tag--info.el-tag--mini.el-tag--light {
  max-width: 100px;
}
</style>
